﻿/*************************************************************************
 * Created by OhZee Creative, LLC
 * 2013
 * This code is licensed under Microsoft Public License (Ms-PL)
 * http://opensource.org/licenses/ms-pl
 * http://ozframework.codeplex.com/
 *************************************************************************/

namespace OhZeeCreative.Windows8.Converters
{
    using System;
    using System.Text;
    using Windows.UI.Xaml.Data;

    public sealed class TimeSpanToStringConverter : IValueConverter
    {
        // These control the decimal places. If 0, no decimal places are specified. If minus, that field is skipped. If you're not careful, you might get unexpected results.
        public int Hours { get; set; }
        public int Minutes { get; set; }
        public int Seconds { get; set; }
        public int Milliseconds { get; set; }

        public TimeSpanToStringConverter()
        {
            this.Hours = 0;
            this.Minutes = 2;
            this.Seconds = 2;
            this.Milliseconds = 3;
        }

        public object Convert(object value, Type targetType, object parameter, string language)
        {
            TimeSpan timeSpan = (TimeSpan)value;

            int hours = timeSpan.Hours;

            StringBuilder format = new StringBuilder();
            ProcessFormat(format, "0", this.Hours, hours > 0 ? "+" : "");
            ProcessFormat(format, "1", this.Minutes, ":");
            ProcessFormat(format, "2", this.Seconds, ":");
            ProcessFormat(format, "3", this.Milliseconds, ".");

            // CAUTION: only hours will have the '-' sign, if any.            
            int minutes = Math.Abs(timeSpan.Minutes);
            int seconds = Math.Abs(timeSpan.Seconds);
            int milliseconds = Math.Abs(timeSpan.Milliseconds);

            return string.Format(format.ToString(), hours, minutes, seconds, milliseconds);
        }

        private void ProcessFormat(StringBuilder format, string placeHolder, int decimalPlaces, string prefix = null)
        {
            if (decimalPlaces >= 0)
            {
                if (prefix != null)
                {
                    format.Append(prefix);
                }
                format.Append("{");
                format.Append(placeHolder);
                if (Hours > 0)
                {
                    format.Append(":");
                    for (int i = 0; i < decimalPlaces; i++)
                    {
                        format.Append("0");
                    }
                }
                format.Append("}");                
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            throw new NotImplementedException();
        }
    }
}
